package com.mkbk.service.impl;

import com.mkbk.mapper.SupplyMapper;
import com.mkbk.model.Supply;
import com.mkbk.service.SupplyService;
import com.mkbk.utils.MybatisUtil;
import org.apache.ibatis.session.SqlSession;

import java.util.List;

public class SupplyServiceImpl implements SupplyService {
    SupplyMapper supplyMapper;

    /**
     * 获取所有的供应商
     */
    @Override
    public List<Supply> getAllSupply(Supply supply) {
        // 开启事务
        SqlSession sqlSession = MybatisUtil.openSession();
        // 获取代理对象
        supplyMapper = sqlSession.getMapper(SupplyMapper.class);
        List<Supply> supplyResult = supplyMapper.getAllSupply(supply.getsName());
        // 提交事务
        sqlSession.commit();
        // 关闭事务
        sqlSession.close();
        return supplyResult;
    }

    /**
     * 添加供应商
     */
    public void addSupply(Supply supply) {
        // 开启事务
        SqlSession sqlSession = MybatisUtil.openSession();
        // 获取代理对象
        supplyMapper = sqlSession.getMapper(SupplyMapper.class);
        supplyMapper.addSupply(supply);
        // 提交事务
        sqlSession.commit();
        // 关闭事务
        sqlSession.close();
    }

    /**
     * 删除供应商
     */
    public void deleteSupplyById(Integer id) {
        // 开启事务
        SqlSession sqlSession = MybatisUtil.openSession();
        // 获取代理对象
        supplyMapper = sqlSession.getMapper(SupplyMapper.class);
        supplyMapper.deleteSupplyById(id);
        // 提交事务
        sqlSession.commit();
        // 关闭事务
        sqlSession.close();
    }

    /**
     * 更新供应商
     */
    public void updateSupplyById(Supply supply) {
        // 开启事务
        SqlSession sqlSession = MybatisUtil.openSession();
        // 获取代理对象
        supplyMapper = sqlSession.getMapper(SupplyMapper.class);
        supplyMapper.updateSupplyById(supply);
        // 提交事务
        sqlSession.commit();
        // 关闭事务
        sqlSession.close();
    }

    /**
     * 分页查询
     */
    public List<Supply> getAllSupplyByPage(Supply supply, int current, int pageSize) {
        // 开启事务
        SqlSession sqlSession = MybatisUtil.openSession();
        // 获取代理对象
        supplyMapper = sqlSession.getMapper(SupplyMapper.class);
        current = (current - 1) * pageSize;
        List<Supply> supplyResult = supplyMapper.getAllSupplyByPage(supply.getsName(), current, pageSize);
        // 提交事务
        sqlSession.commit();
        // 关闭事务
        sqlSession.close();
        return supplyResult;
    }
}
